﻿using EventBus.Abstractions;
using Microsoft.Extensions.Logging;
using Payment.API.Application.IntegrationEvents;
using Payment.API.Application.IntegrationEvents.Events;
using Payment.API.Application.Repositories;
using Payment.API.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Payment.API.Application.Services
{
    public class PaymentService : IPaymentService
    {
        private readonly IPaymentRepository _paymentRepository;
        private readonly IEventBus _eventBus;
        private readonly ILogger<PaymentService> _logger;
        private readonly IPaymentIntegrationEventService _paymentIntegrationEventService;
        public PaymentService(IPaymentRepository paymentRepository,
            IEventBus eventBus,
            ILogger<PaymentService> logger,
            IPaymentIntegrationEventService paymentIntegrationEventService)
        {
            _paymentRepository = paymentRepository ?? throw new ArgumentNullException(nameof(paymentRepository));
            _eventBus = eventBus ?? throw new ArgumentNullException(nameof(eventBus));
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
            _paymentIntegrationEventService = paymentIntegrationEventService ?? throw new ArgumentNullException(nameof(paymentIntegrationEventService));
        }
        public async Task<bool> PaySucceededAsync(List<string> orderIds,string userId)
        {
            foreach(var orderId in orderIds)
            {
                PaymentLog log = new PaymentLog(orderId, 0, userId);
                await _paymentRepository.AddPaymentLogAsync(log);
            }
            OrderPaymentSucceededIntegrationEvent orderPaymentIntegrationEvent = new OrderPaymentSucceededIntegrationEvent(orderIds);
            await _paymentIntegrationEventService.SaveEventAndPaymentContextChangesAsync(orderPaymentIntegrationEvent);
            await _paymentIntegrationEventService.PublishThroughEventBusAsync(orderPaymentIntegrationEvent);
            return await Task.FromResult(true);
            //await _eventBus.Publish();
        }
    }
}
